package pl.edu.agh.iosr.gamblingzone.userpanel.action;

import static org.jboss.seam.ScopeType.SESSION;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

import pl.edu.agh.iosr.gamblingzone.model.AbstractEvent;
import pl.edu.agh.iosr.gamblingzone.model.Bet;
import pl.edu.agh.iosr.gamblingzone.model.BettingSlip;
import pl.edu.agh.iosr.gamblingzone.model.Participant;

@Stateful
@Name("betsFromSlip")
@Scope(SESSION)
@Restrict("#{identity.loggedIn}")
public class BetViewAction implements BetView {

	@PersistenceContext
	private EntityManager em;
	
	@In(required=false) @Out
	private BettingSlip slip;
	
	@In
	private FacesMessages facesMessages;
	      
	@In
	private Events events;
	
	@Logger
	Log log;
	
	@DataModel
	private List<Bet> bets;
	
	@DataModel
	private Set<AbstractEvent> eventsOnBet;
	
	@DataModel
	private List<Participant> participants;
	
	public void selectBettingSlip(BettingSlip bettingSlip) {
		log.info("metoda select");
		bettingSlip = em.merge(bettingSlip);
		
		bets = bettingSlip.getBets();
		
		for (Bet bet : bets) {
			em.refresh(bet);			
			mergeEvents(bet);
			mergeParticipant(bet);
		}
	}
	
	private void mergeEvents(Bet bet) {
		bet = em.merge(bet);
		eventsOnBet = bet.getEvents();
		for (AbstractEvent event : eventsOnBet) {
			em.refresh(event);
			mergeEventParticipants(event);
		}
		
		log.info("num of event " + eventsOnBet.size());
	}
	
	private void mergeParticipant(Bet bet) {
		Participant participant = bet.getWinner();
		em.merge(participant);
	}
	
	private void mergeEventParticipants(AbstractEvent event) {
		participants = new LinkedList<Participant>(event.getRates().values());
		for (Participant participant : participants) {
			em.merge(participant);
		}
	}
	
	@Remove
	public void destroy() {
	}

}
